package com.rew.canteenbox.fragments;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.rew.canteenbox.R;
import com.rew.canteenbox.activities.InfoActivity;
import com.rew.canteenbox.adapter.DishesMenuAdapter;
import com.rew.canteenbox.bases.AppData;
import com.rew.canteenbox.functions.ScroRefeshListView;
import com.rew.canteenbox.models.Dishes;

import java.util.List;

/**
 *  Fragment_Menu.
 *
 * Created by HuiWen Ren on 2016/11/4.
 */
public class FMenu extends Fragment {

    private AppData appData;

    private DishesMenuAdapter adapter;

    private View view;

    private Dishes dishes;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_menu, container,false);
        appData = (AppData) getActivity().getApplication();
        init();
        return view;
    }

    private void init(){

        List<Dishes> dishesList = appData.getDishesList();

        // 设置adapter.
        adapter = new DishesMenuAdapter(getActivity(),
                                        R.layout.item_dish, dishesList);
        ScroRefeshListView listView = (ScroRefeshListView) view.findViewById(R.id.list_view);
        // 列表与adapter连接(初始化).
        listView.setAdapter(adapter);
        // 设置点击监听.
        listView.setOnItemClickListener((parent, view, position, id) -> {
            dishes = dishesList.get(position - 1);
            InfoActivity.actionStart(getActivity(), dishes.getDishName());
        });

        listView.setonRefreshListener(() -> new AsyncTask<Void, Void, Void>() {
            protected Void doInBackground(Void... params) {
                try {
                    // 模拟延时.
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                adapter.notifyDataSetChanged();
                listView.onRefreshComplete();
            }
        }.execute(null, null, null));
    }
}